package com.cyx.exception;

import com.cyx.pojo.Dept;
import com.cyx.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler
    public Result handleException(Exception e){
        log.error("程序出错啦~",e);
        return Result.error("程序出错,请联系管理员");
    }
    @ExceptionHandler
    public Result handleDuplicateKeyException(DuplicateKeyException e){
        log.error("程序出错啦~",e);
        String message = e.getMessage();
        int i = message.indexOf("Duplicate entry");
        String errMsg = message.substring(i);
        String[] arr = errMsg.split(" ");
        return Result.error(arr[2] + " 已存在");
    }
    @ExceptionHandler
    public Result handleClazzHasStudentsException(ClassHasStudentsException e){
        log.error("班级删除异常: {}",e.getMessage());
        return Result.error(e.getMessage());
    }

    /**
     *  删除部门异常 部门下有员工 不删除该部门
     */

    @ExceptionHandler
    public Result handleDeptHasEmpException(DeptHasEmpException e){
        log.error("部门删除异常：{}",e.getMessage());
        return Result.error(e.getMessage());
    }
}
